/*********************************************************************
Copyright 2003 © Victor Company of Japan, Limited All Right Reserved.
The following JavaScript for the XML Service Manual includes our
patent-pending algorithm.
**********************************************************************/

/***********
** JVC SVG Viewerカスタマイズスクリプト
***********/

copyright = 'Copyright 2003 © Victor Company of Japan, Limited All Rights Reserved.';
patent = 'The XML Service Manual includes our patent-pending algorithm.';
//svgFunction_js = '1.1.0';		// 2003.05.22 - I.NUNO
//svgFunction_js = '1.2.0';		// 2003.06.03 - I.NUNO
svgFunction_js = '1.3.0';		// 2003.06.08 - I.NUNO
parts_js = '';

/************
**  デフォルトコンテキスト設定
************/
function menuSet() {
	var context = '<menu>';
	context += '<header>JVC Custom Menu</header>';
	context += '<item onactivate="aboutCopyrightInfo()" id="JvcMenu">JVC Menu</item>';
	context += '<separator/>';
	context += '<item enabled="no" id="PartsSelect">(undefined)</item>';
	context += '<separator/>';
	// マイノートメニュー
	context += '<item enabled="no" id="MyNote">My Note</item>';
	// お気に入りメニュー
	context += '<item enabled="no" id="MyFavoriteLink">My Favorite Link</item>';
	context += '<separator/>';
	// 透過モードメニュー
	context += '<item onactivate="changeOpacity()" id="TransparentView" checked="no">Transparent View</item>';
	// コメント表示メニュー
	if (document.getElementById('z|annotation') == null) {
		context += '<item id="CommentView" enabled="no">Comment View</item>';
	} else {
		context += '<item onactivate="changeComment()" id="CommentView" checked="yes">Comment View</item>';
	}
	// 図面反転
	context += '<item onactivate="reverse()" id="ReversedView" checked="no">Reversed View</item>';
	// レイヤーメニュー
	context += '<menu id="LayerSelection">';
		context += '<header>Layer View</header>';
		context += '<item onactivate="showAllLayers()" id="AllLayers" enabled="no">All Layers</item>';
		context += '<separator/>';
		var layerG = rootG.firstChild;
		while (layerG != null) {
			if (layerG.nodeName == 'g') {
				context += '<item onactivate="changeLayer(\'' + layerG.id + '\')" id="' + layerG.id + '" checked="yes">' + layerG.getAttribute(":name") + '</item>';
				layerMenuChecked[layerG.id] = "yes";
				allLayerG.push(layerG);
			}
			layerG = layerG.nextSibling;
		}
	context += '</menu>';
	//context += '<item action="Open" id="Open">Open</item>';
	//context += '<item action="OpenNew" id="OpenNew">Open in New Window</item>';
	context += '<separator/>';
	// 印刷メニュー
	context += '<item onactivate="browserEval(\'window.print()\')" id="Print">Print Screen...</item>';
	context += '<separator/>';
	context += '<item action="ZoomIn" id="ZoomIn">Zoom &amp;In</item>';
	context += '<item action="ZoomOut" id="ZoomOut">Zoom &amp;Out</item>';
	//context += '<item action="OriginalView()" id="OriginalView">Original Vie&amp;w</item>';
	context += '<item onactivate="showOriginalView()" id="OriginalView">Original Vie&amp;w</item>';
	context += '<separator/>';
	context += '<item action="Quality" id="Quality">Higher &amp;Quality</item>';
	context += '<item action="Pause" id="Pause">&amp;Pause</item>';
	//context += '<item action="Mute" id="Mute">&amp;Mute</item>';
	context += '<separator/>';
	// 部品検索
	context += '<item onactivate="inputPart()">Find Parts...</item>';
	context += '<item action="Find" id="Find" checked="no">&amp;Find Text...</item>';
	context += '<item action="FindAgain" id="FindAgain">Find Text &amp;Again</item>';
	context += '<separator/>';
	context += '<item action="Copy" id="Copy">&amp;Copy Selected Text</item>';
	//context += '<item action="CopySVG" id="CopySVG">&amp;Copy SVG</item>';
	context += '<item action="ViewSVG" id="ViewSVG">View SV&amp;G...</item>';
	//context += '<item action="ViewSource" id="ViewSource">&amp;View Source...</item>';
	context += '<item action="SaveAs" id="SaveAs">&amp;Save SVG As...</item>';
	context += '<separator/>';
	// 図面情報表示
	context += '<item onactivate="aboutDrawingInfo()">About Drawing...</item>';
	context += '<separator/>';
	context += '<item action="Help" id="Help">&amp;Help...</item>';
	context += '<item action="About" id="About">A&amp;bout Adobe SVG Viewer...</item>';
	context += '</menu>';
	
	var newMenuRoot = parseXML(context, contextMenu);
	contextMenu.replaceChild(newMenuRoot, contextMenu.firstChild);
}

/************
**  オリジナル表示
************/
function showOriginalView() {
	svgG.currentScale = 1;
	svgG.currentTranslate.y = 0;
	if (rootG.getCTM.a == 1) {
		svgG.currentTranslate.x = 0;
	} else {
		var unitPerPixel,viewMidX;
		viewMidX = Number(viewBox[0]) + Number(viewBox[2]/2);
		if (viewBox[2]/viewBox[3] > innerWidth/innerHeight) {
			// windowが縦長
			unitPerPixel = viewBox[2]/innerWidth;
		} else {
			// windowが横長
			unitPerPixel = viewBox[3]/innerHeight;
		}
		svgG.currentTranslate.x = viewMidX*2/unitPerPixel;
	}
}

/************
**  ViewBox 読み取り
************/
function readViewBox() {
	var s;
	s = document.firstChild.getAttribute('viewBox');
	viewBox = s.split(' ');
}
/************
**  透過モード切替
************/
function changeOpacity() {
	if (rootG.getAttribute('fill-opacity') != '0.5') {
		rootG.setAttribute('fill-opacity', '0.5');
	} else {
		rootG.setAttribute('fill-opacity', '1');
	}
	UpdateMenu('TransparentView', 'checked', null, false);
}

/************
**  コメント表示切替
************/
function changeComment() {
	if (document.getElementById('z|annotation').getAttribute('visibility') == 'hidden') {
		document.getElementById('z|annotation').setAttribute('visibility', 'visible');
	} else {
		document.getElementById('z|annotation').setAttribute('visibility', 'hidden');
	}
	UpdateMenu('CommentView', 'checked', null, false);
}

/************
**  レイヤー表示切替
************/
function changeLayer(id) {
	var j = 1;
	if (allLayerChecked == true) {
		for (i in layerMenuChecked) {
			if (layerMenuChecked[i] == 'yes') {
				j++;
			}
		}
	}
	
	if (layerMenuChecked[id] == 'yes') {
		layerMenuChecked[id] = 'no';
		document.getElementById(id).setAttribute('visibility', 'hidden');
		if (allLayerChecked == false) {
			allLayerChecked = !allLayerChecked;
			UpdateMenu('AllLayers', 'enabled', 'LayerSelection', false);
		}
	} else {
		layerMenuChecked[id] = 'yes';
		document.getElementById(id).setAttribute('visibility', 'visible');
		if (j == allLayerG.length) {
			allLayerChecked = !allLayerChecked;
			UpdateMenu('AllLayers', 'enabled', 'LayerSelection', false);
		}
	}
	UpdateMenu(id, 'checked', 'LayerSelection', false);
}

/************
**  全レイヤー表示
************/
function showAllLayers() {
	var id;
	for (id in layerMenuChecked) {
		if (layerMenuChecked[id] == 'no') {
			layerMenuChecked[id] = 'yes';
			document.getElementById(id).setAttribute('visibility', 'visible');
			UpdateMenu(id, 'checked', 'LayerSelection', false);
		}
	}
	
	allLayerChecked = !allLayerChecked;
	UpdateMenu('AllLayers', 'enabled', 'LayerSelection', false);
}

/************
** 発注ウィンドウ表示
************/
function showOrderWindow(key, pno) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	if(frame_name == 'frame0'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showPartsOrder('" + key + "','" + pno + "','" + svg_name + "', null)}");
	}else if(frame_name == 'frame1'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showPartsOrder('" + key + "','" + pno + "',null,'" + svg_name + "')}");
	}
}

/************
** データシートウィンドウ表示
************/
function showDataSheetWindow(key, pno){
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	if(frame_name == 'frame0'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showDataSheet('" + key + "','" + pno + "','" + svg_name + "', null)}");
	}else if(frame_name == 'frame1'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showDataSheet('" + key + "','" + pno + "',null,'" + svg_name + "')}");
	}
}

/************
**  マイノート入力画面表示
************/
function showMyNoteInput(targetModel) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	var selectedsymbol;
	if (selected != null) {
		selectedsymbol = selected;
	} else {
		selectedsymbol = "";
	}
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showMyNote('" + svg_name + "','" + targetModel + "','" + blockId + "','" + selectedsymbol + "')}");
}

/************
**  マイノート一覧画面表示
************/
function showNoteList(type) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	if (type == null) {
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showMyNoteList('" + svg_name + "')}");
	} else {
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showMyNoteList('')}");
	}
}

/************
**  図形非選択
************/
function cancelPart() {
	if (parent.name == '') {
		cancel(selected);
	}
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.searchParts(null,null,null)}");
}

/************
**  図形クリック時イベント
************/
function click(evt) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	var parts = getParts(evt.target);
	if (selected != null) {
		cancel(selected);
	}
	if (selected != parts) {
		if (frame_name == 'frame0') {
			browserEval("if(parent != null && parent.frame2 != null){parent.frame2.searchParts('" + parts + "','" + svg_name + "', null)}");
		} else if (frame_name == 'frame1') {
			browserEval("if(parent != null && parent.frame2 != null){parent.frame2.searchParts('" + parts + "',null,'" + svg_name + "')}");
		} else {
			select(parts, '');
		}
	} else {
		selected = null;
	}
}

/************
**  パーツ名入力検索
************/
function inputPart(){
	var key = prompt("Please input symbol number.","")
	if( key == "" || key == null ){
		return;
	}
	
	key = key.toUpperCase();
	
	var sep2 = "P?";
	var sep3 = "N?";
	var searchType;
	
	searchType = "ref";
	if (key.indexOf(sep2, 0) >= 0) {
		searchType = "number";
	} else if (key.indexOf(sep3, 0) >= 0) {
		searchType = "name";
	} else {
		searchType = "ref";
	}
	
	if (searchType == "ref") {
		var keys = ["", key];
	} else if (searchType == "number") {
		var keys = key.split(sep2);
	} else if (searchType == "name") {
		var keys = key.split(sep3);
	}
	
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	var res = getPartsBBox(key);
	if (res != null) {
		if (parent.name == '') {
			select(key, '');
		}
		focusBBox(getPartsBBox(key));
	}
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.globalSerachParts('" + searchType + "', '" + keys[1] + "')}");
}

/************
**  パーツ取得
************/
function getPartsName(name) {
	var g = elem.parentNode;
	while (!g.hasAttribute(':l') && !g.hasAttribute(':name')) {
		g = g.parentNode;
	}
	var parts = g.getAttribute(':l');
	return parts.split('|')[0];
}

/************
**  パーツ名取得
************/
function getParts(elem) {
	var g = elem.parentNode;
	while (!g.hasAttribute(':l') && !g.hasAttribute(':name')) {
		g = g.parentNode;
	}
	var parts = g.getAttribute(':l');
	return parts.split('|')[0];
}

/************
**  パーツ色選択
************/
function selectColor() {
	var color;
	var cacheItem;
	
	if (selected != null) {
		cacheItem = cache[selected];
		for (color in cacheItem) {
			var g;
			g = cacheItem[color];
			if (g.hasAttribute('z:cf')) { 
				defaultColor = g.getAttribute('z:cf');
			}
			if (g.hasAttribute('z:cs')) { 
				defaultColor = g.getAttribute('z:cs');
			}
		}
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.colorDialog('" + defaultColor +"','" + parent.name + "')}");
	}
}

/************
**  パーツ色変更
************/
function changeColor(col) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	var color;
	var cacheItem;
	
	if (selected != null) {
		cacheItem = cache[selected];
		for (color in cacheItem) {
			var g;
			g = cacheItem[color];
			if (g.hasAttribute('z:cf')) { 
				g.setAttribute('z:cf', col);
				g.setAttribute('fill', col);
			}
			if (g.hasAttribute('z:cs')) { 
				g.setAttribute('z:cs', col);
				g.setAttribute('stroke', col);
			}
			//cancelPart();
			browserEval("if(parent != null && parent.frame2 != null){parent.frame2.saveMyDraw('" + svg_name + "','" + selected + "','" + col + "')}");
		}
	}
}

/************
**  パーツ選択解除
************/
function cancel(parts) {
	var color;
	var cacheItem;
	 
	cacheItem = cache[parts];
	
	for (color in cacheItem) {
		var g;
		g = cacheItem[color];
		if (g.hasAttribute('z:cf')) { 
			g.setAttribute('fill', g.getAttribute('z:cf'));
		}
		if (g.hasAttribute('z:cs')) { 
			g.setAttribute('stroke', g.getAttribute('z:cs'));
		}
		g.removeChild(g.firstChild);
	}
	
	// メニュー制御
	var context = '<item enabled="no" id="PartsSelect">(undefined)</item>';
	var appendMenu = parseXML(context, contextMenu);
	var menuRoot = contextMenu.firstChild;
	menuRoot.replaceChild(appendMenu, menuRoot.childNodes.item(3));
	
	var frame_name = parent.name;
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.defaultContextMemu('" + parent.name + "','"  + svg_name + "','','')}");
	selected = null;
}

/************
**  パーツ選択
************/
function select(parts, draw) {
	if (scriptenable != 1) {
		return;
	}
	cancel(selected);
	if (parts == null || parts == ''){
		return;
	}
	
	var layer,partsG,color,pid,cacheItem;
	
	if (cache[parts] != null) {
		cacheItem = cache[parts];
		for (color in cacheItem) {
			var g;
			g = cacheItem[color];
			if (g.hasAttribute('fill')&&(g.getAttribute('fill')!='none')) { 
				g.setAttribute('fill', 'red');
			}
			if (g.hasAttribute('stroke')&&(g.getAttribute('fill')!='stroke')) { 
				g.setAttribute('stroke', 'red');
			}
			g.insertBefore(animT.cloneNode(false), g.firstChild);
		}
	} else {
		var parts_piped = '|' + parts.toLowerCase() + '|';
		cacheItem = new Array;
		layer = rootG.firstChild;
		while (layer != null) {
			if (layer.nodeName == 'g') {
				partsG = layer.firstChild;
				while (partsG != null) {
					if (partsG.nodeName == 'g') {
						pid = '|' + partsG.getAttribute(':l').toLowerCase() + '|' ;
						if (pid.indexOf(parts_piped) != -1) {
							color = partsG.firstChild;
							while (color != null) {
								if (color.hasAttribute('fill')&&(color.getAttribute('fill')!='none')) { 
									color.setAttribute('z:cf', color.getAttribute('fill')); 
									color.setAttribute('fill', 'red');
								}
								if (color.hasAttribute('stroke')&&(color.getAttribute('fill')!='stroke')) { 
									color.setAttribute('z:cs', color.getAttribute('stroke')); 
									color.setAttribute('stroke', 'red');
								}
								cacheItem.push(color);
								color.insertBefore(animT.cloneNode(false), color.firstChild);
								color = color.nextSibling;
							}
						}
					}
					partsG = partsG.nextSibling;
				}
			}
			layer = layer.nextSibling;
		}
		if (cacheItem.length == 0) {
			if (draw == 0)
				alert('There is not the part in this schematic diagram.');
			else if (draw == 1)
				alert('There is not the part on this circuit board.');
			return;
		}
		cache[parts] = cacheItem;
	}
	selected = parts;
	
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	if(frame_name == 'frame0'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showPartsContextMemu('" + parts + "','" + svg_name + "', null)}");
	}else if(frame_name == 'frame1'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showPartsContextMemu('" + parts + "', null, '" + svg_name + "')}");
	}
}

/************
**  部品選択時コンテキストメニュー更新
************/
function partsMenuUpdate(parts, blockno, pno, enDataSheet, enPartsMark) {
	var context = '<menu id="PartsSelect">';
	context += '<header>"' + parts + '"</header>';
	
	if (parent.name != '') {
		if (pno.length > 1) {
			context += '<menu id="OrderThis">';
			context += '<header>Order this...</header>';
			for (var i = 0; i < pno.length; i++) {
				context += '<item onactivate="showOrderWindow(\'' + parts + '\',\'' + pno[i] + '\')">' + pno[i] + '</item>';
			}
			context += '</menu>';
		} else {
			if (pno != '') {
				context += '<item onactivate="showOrderWindow(\'' + parts + '\',\'' + pno + '\')">Order this...</item>';
			} else {
				context += '<item enabled="no">Order this...</item>';
			}
		}
		
		if (enDataSheet.length > 1) {
			context += '<menu id="DataSheet">';
			context += '<header>Data Sheet</header>';
			for (var i = 0; i < enDataSheet.length; i++) {
				if (enDataSheet[i] == true) {
					context += '<item onactivate="showDataSheetWindow(\'' + parts + '\',\'' + pno[i] + '\')">' + pno[i] + '</item>';
				} else {
					context += '<item enabled="no">' + pno[i] + '</item>';
				}
			}
			context += '</menu>';
		} else {
			if (enDataSheet[0] == true) {
				context += '<item onactivate="showDataSheetWindow(\'' + parts + '\',\'' + pno[0] + '\')">Data Sheet</item>';
			} else {
				context += '<item enabled="no">Data Sheet</item>';
			}
		}
	} else {
		context += '<item enabled="no">Order this...</item>';
		context += '<item enabled="no">Data Sheet</item>';
	}
	context += '<separator/>';
	context += '<item onactivate="focusBBox(getPartsBBox(\'' + parts + '\'))">Centering</item>';
	context += '<item onactivate="cancelPart()">Unselect this</item>';
//	if (parent.name == 'frame0') {
	context += '<separator/>';
	if ((browserVersion >= 6) && (parent.name != '')) {
		context += '<item onactivate="selectColor()">Change Color...</item>';
	} else {
		// for IE 5.5
		context += '<menu id="ColorChange">';
		context += '<header>Change Color</header>';
			context += '<item onactivate="changeColor(\'Red\')">Red</item>';
			context += '<item onactivate="changeColor(\'Yellow\')">Yellow</item>';
			context += '<item onactivate="changeColor(\'Lime\')">Lime</item>';
			context += '<item onactivate="changeColor(\'Aqua\')">Aqua</item>';
			context += '<item onactivate="changeColor(\'Blue\')">Blue</item>';
			context += '<item onactivate="changeColor(\'Fuchsia\')">Fuchsia</item>';
			context += '<item onactivate="changeColor(\'Maroon\')">Maroon</item>';
			context += '<item onactivate="changeColor(\'Olive\')">Olive</item>';
			context += '<item onactivate="changeColor(\'Green\')">Green</item>';
			context += '<item onactivate="changeColor(\'Teal\')">Teal</item>';
			context += '<item onactivate="changeColor(\'Navy\')">Navy</item>';
			context += '<item onactivate="changeColor(\'Purple\')">Purple</item>';
			context += '<item onactivate="changeColor(\'Black\')">Black</item>';
		context += '</menu>';
	}
	context += '<separator/>';
	if (enPartsMark == true) {
		context += '<item onactivate="setMark(\'' + parts + '\',\'' + blockno + '\')">Mark</item>';
	} else {
		context += '<item enabled="no">Mark</item>';
	}
	
	context += '</menu>';
	
	var appendMenu = parseXML(context, contextMenu);
	
	var menuRoot = contextMenu.firstChild;
	menuRoot.replaceChild(appendMenu, menuRoot.childNodes.item(3));
}

/************
**  部品マーク設定
************/
function setMark(parts, blockno) {
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.setPartsMark('" + parts + "','" + blockno + "')}");
}

/************
**  図面逆転
************/
function reverse() {
	// 図面反転
	if (rootG.hasAttribute('transform')) {
		// X軸逆転解除
		rootG.removeAttribute('transform');
		// Layerの順序を逆にする
		for (var i = 1; i < allLayerG.length; i++) {
		  rootG.appendChild(rootG.removeChild(allLayerG[i]));
		}
	} else {
		// X軸逆転
		rootG.setAttribute('transform', 'matrix(-1 0 0 1 0 0)');
		// Layerの順序を逆にする
		for (var i = allLayerG.length - 2; i >= 0; i--) {
		  rootG.appendChild(rootG.removeChild(allLayerG[i]));
		}
	}
	// コメント反転
	var commentG = document.getElementById('z|annotation');
	if (commentG != null) {
		var elem = commentG.firstChild;
		var elem2;
		if (commentG.hasAttribute('transform')) {
			// 反転解除
			commentG.removeAttribute('transform');
			while (elem != null) {
				if (elem.nodeName == 'text') {
					elem.removeAttribute('transform');
				} else if (elem.nodeName == 'g') {
					elem2 = elem.firstChild.nextSibling;  // landmark<text>狙い撃ち
					elem2.removeAttribute('transform');
				}
				elem = elem.nextSibling;
			}
		} else {
			// 反転(textは反転せず移動のみ)
			commentG.setAttribute('transform', 'matrix(-1 0 0 1 0 0)');
			while (elem != null) {
				if (elem.nodeName == 'text') {
					elem.setAttribute('transform', 'matrix(-1 0 0 1 ' + (elem.getBBox.x*2 + elem.getBBox.width) + ' 0)');
				} else if (elem.nodeName == 'g') {
					elem2 = elem.firstChild.nextSibling; // landmark<text>狙い撃ち
					elem2.setAttribute('transform', 'matrix(-1 0 0 1 ' + (elem2.getBBox.x*2 + elem2.getBBox.width) + ' 0)');
				}
				elem = elem.nextSibling;
			}
		}
	}
	// 安全指定部品反転
	var commentG = document.getElementById('z|safty');
	if (commentG != null) {
		var elem = commentG.firstChild;
		var elem2;
		if (commentG.hasAttribute('transform')) {
			// 反転解除
			commentG.removeAttribute('transform');
			while (elem != null) {
				elem.removeAttribute('transform');
				elem = elem.nextSibling;
			}
		} else {
			commentG.setAttribute('transform', 'matrix(-1 0 0 1 0 0)');
			while (elem != null) {
				elem.setAttribute('transform', 'matrix(-1 0 0 1 ' + (elem.getBBox.x*2 + elem.getBBox.width) + ' 0)');
				elem = elem.nextSibling;
			}
		}
	}
	showOriginalView();
	UpdateMenu('ReversedView', 'checked', null, false);
}

/************
**  BBoxをフォーカス
************/
function focusBBox(bBox) {
	if (scriptenable != 1) {
		return;
	}
	
	var unitPerPixel, orgX, orgY, transX, transY, scale;
	var x,y,width,height;
	
	if (bBox == null) {
		return;
	}
	
	if (rootG.getCTM.a == 1) {
		// 通常時
		x=bBox.x;
		y=bBox.y;
		width=bBox.width;
		height=bBox.height;
	} else {
		// 反転時
		x=-bBox.x-bBox.width;
		y=bBox.y;
		width=bBox.width;
		height=bBox.height;
	}
	// translateが0,0になる点の論理座標を取得
	if (viewBox[2]/viewBox[3] > innerWidth/innerHeight) {
		// windowが縦長
		unitPerPixel=viewBox[2]/innerWidth;
		orgX=viewBox[0];
		orgY=(Number(viewBox[1])+Number(viewBox[3])/2)-innerHeight/2*unitPerPixel;
	} else {
		// windowが横長
		unitPerPixel=viewBox[3]/innerHeight;
		orgX=(Number(viewBox[0])+Number(viewBox[2])/2)-innerWidth/2*unitPerPixel;
		orgY=viewBox[1];
	}
	// BBoxに合わせてfocus移動
	scale = svgG.currentScale;
//	if (width/height > innerWidth/innerHeight) {
//		scale=unitPerPixel/width*innerWidth;
//	} else {
//		scale=unitPerPixel/height*innerHeight;
//	}
//	if (scale > 32) scale = 32; // scaleがでかすぎるとSVGViewerがバグる
	transX = (orgX-((x+width/2)-innerWidth/scale/2*unitPerPixel))/unitPerPixel*scale;
	transY = (orgY-((y+height/2)-innerHeight/scale/2*unitPerPixel))/unitPerPixel*scale;
	
	if (Math.abs(transX) > 14000) { // translateの値がでかすぎるとSVGViewerがバグる
//		scale=scale*(14000/Math.abs(transX));
		transX = (orgX-((x+width/2)-innerWidth/scale/2*unitPerPixel))/unitPerPixel*scale;
		transY = (orgY-((y+height/2)-innerHeight/scale/2*unitPerPixel))/unitPerPixel*scale;
	}
	if (Math.abs(transY) > 14000){
//		scale=scale*(14000/Math.abs(transY));
		transX = (orgX-((x+width/2)-innerWidth/scale/2*unitPerPixel))/unitPerPixel*scale;
		transY = (orgY-((y+height/2)-innerHeight/scale/2*unitPerPixel))/unitPerPixel*scale;
	}
//	svgG.currentScale=scale;
	svgG.currentTranslate.x = transX;
	svgG.currentTranslate.y = transY;
}

/************
**  partsのBBoxを取得
************/
function getPartsBBox(parts) {
	if (scriptenable != 1) {
		return;
	}
	
	var layer,partsG,pid,bBox,partsBBox,minX,minY,maxX,maxY;
	
	if (cacheBBox[parts] != null) {
		return cacheBBox[parts];
	} else {
		var parts_piped = '|' + parts + '|';
		layer = rootG.firstChild;
		while (layer != null) {
			if (layer.nodeName == 'g') {
				partsG = layer.firstChild;
				while (partsG != null) {
					if (partsG.nodeName == 'g') {
						pid = '|' + partsG.getAttribute(':l') + '|';
						if (pid.indexOf(parts_piped) != -1) {
							partsBBox=partsG.getBBox;
							if (minX>partsBBox.x || minX==null) minX=partsBBox.x;
							if (minY>partsBBox.y || minY==null) minY=partsBBox.y;
							if (maxX<partsBBox.x+partsBBox.width || maxX==null) maxX=partsBBox.x+partsBBox.width;
							if (maxY<partsBBox.y+partsBBox.height || maxY==null) maxY=partsBBox.y+partsBBox.height;
						}
					}
					partsG = partsG.nextSibling;
				}
			}
			layer = layer.nextSibling;
		}
		
		bBox = svgG.createSVGRect;
		if(minX == null || minY == null || maxX == null || maxY == null){
			return null;
		}
		bBox.x = minX;
		bBox.y = minY;
		bBox.width = maxX-minX;
		bBox.height = maxY-minY;
		cacheBBox[parts] = bBox;
		return bBox;
	}
}

/************
**  ランドマーク対応
************/
function landmark(file){
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.searchDraw('" + file + "')}else{window.open('" + file + ".svgz', '_self')}");
}

/************
**  図面情報表示
************/
function aboutDrawingInfo() {
	var info = '';
	info += 'Manual No.\t' + manualId + '\n';
	info += 'Model Name\t' + manualTitle + '\n';
	info += 'Block No.\t\t' + blockId + '\n';
	info += 'Drawing Name\t' + drawingTitle + '\n';
//	info += 'Drawing ID\t' + drawingId + '\n';
	info += 'Drawing Version\t' + drawingVer + '\n';
	info += 'Drawing Time Stamp\t' + drawingTimestamp + '\n';
//	info += '\n';
//	info += 'svgFunction.js Ver\t' + svgFunction_js;
	if (scriptenable == 1) {
		info += 'Script Enable\t' + 'True';
	} else {
		info += 'Script Enable\t' + 'False';
	}
	
	alert(info);
}

/************
**  著作権、バージョン情報表示
************/
function aboutCopyrightInfo() {
	var info = '';
	info += copyright + '\n';
	info += patent + '\n\n';
	info += 'svgFunction.js\tVer.' + svgFunction_js;
	if (parts_js != '' ) {
		info += '\nparts.js\t\tVer.' + parts_js;
	}
	
	alert(info);
}

/************
**  マイノートコンテキストメニュー更新
************/
function MyNoteMenuUpdate(enabled, targetModel) {
	var context ='';
	if (enabled == false) {
		context += '<item enabled="no" id="MyNote">My Note</item>';
	} else {
		context += '<menu id="MyNote">';
		context += '<header>My Note</header>';
			if (targetModel.length > 1) {
				context += '<menu id="MyNoteModel">';
				context += '<header>Input...</header>';
				for (var i = 0; i < targetModel.length; i++) {
					context += '<item onactivate="showMyNoteInput(\'' + targetModel[i] + '\')">' + targetModel[i] + '</item>';
				}
				context += '</menu>';
			} else {
				context += '<item onactivate="showMyNoteInput(\'' + targetModel + '\')">Input...</item>';
			}
			context += '<item onactivate="showNoteList(null)">List...</item>';
			context += '<item onactivate="showNoteList(\'all\')">All List...</item>';
		context += '</menu>';
	}
	var appendMenu = parseXML(context, contextMenu);
	
	var menuRoot = contextMenu.firstChild;
	menuRoot.replaceChild(appendMenu, menuRoot.childNodes.item(5));
}

/************
**  お気に入りコンテキストメニュー更新
************/
function favoriteMenuUpdate(FavoriteName, FavoriteSubName) {
	var context ='';
	if (FavoriteName.length < 2) {
		context += '<item enabled="no" id="MyFavoriteLink">My Favorite Link</item>';
	} else {
		context += '<menu id="MyFavoriteLink">';
		context += '<header>My Favorite Link</header>';
		for (var i = 1; i <	FavoriteName.length; i++) {
			if (FavoriteName[i] != "") {
				if (FavoriteSubName[i].length > 1) {
					context += '<menu id="MyFavoriteLinkSub">';
					context += '<header>' + FavoriteName[i] + '</header>';
					for (var j = 0; j < FavoriteSubName[i].length; j++) {
						context += '<item onactivate="showFavorite(' + i + ',\'' + FavoriteSubName[i][j] + '\')" id="Favorite' + i + '">' + FavoriteSubName[i][j] + '</item>';
					}
					context += '</menu>';
				} else {
					context += '<item onactivate="showFavorite(' + i + ',\'\')" id="Favorite' + i + '">' + FavoriteName[i] + '</item>';
				}
			}
		}
		context += '</menu>';
	}
	var appendMenu = parseXML(context, contextMenu);
	
	var menuRoot = contextMenu.firstChild;
	menuRoot.replaceChild(appendMenu, menuRoot.childNodes.item(6));
}

/************
**  お気に入りメニュー表示
************/
function showFavorite(num, targetSub) {
	var frame_name = parent.name;	// 今クリックしたフレームの名前
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	
	var selectedsymbol;
	if (selected != null) {
		selectedsymbol = selected;
	} else {
		selectedsymbol = "";
	}
	if(frame_name == 'frame0'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showFavoriteWindow(" + num + ",'" + selectedsymbol + "','" + targetSub + "','" + svg_name + "',null)}");
	}else if(frame_name == 'frame1'){
		browserEval("if(parent != null && parent.frame2 != null){parent.frame2.showFavoriteWindow(" + num + ",'" + selectedsymbol + "','" + targetSub + "',null,'" + svg_name + "')}");
	}
}

/************
**  コンテキストメニューオプション対応
************/
function UpdateMenu(optionName, optionType, optionSubmenu, exclusive) {
	var optionValue;
	var eachItem;
	var eachSubItem;
	var on;
	var off;
	
	switch (optionType) {
		case 'checked':
		case 'enabled':
			on = 'yes';
			off = 'no';
			break;
		case 'display':
			on = 'inline';
			off = 'none';
			break;
	}
	
	var menuItems = contextMenu.childNodes.item(0).childNodes;
	
	for (i = 0; i < menuItems.length; i++) {
		if (1 == menuItems.item(i).nodeType) {
			eachItem = menuItems.item(i);
			if (null == optionSubmenu) {
				if (optionName == eachItem.getAttribute('id')) {
					targetItem = eachItem;
					if (null != optionType) {
						optionValue = targetItem.getAttribute(optionType);
					}
				}
			} else if ((eachItem.nodeName == 'menu') && (optionSubmenu == eachItem.getAttribute('id'))) {
				submenuItems = eachItem.childNodes;
				
				for (j = 0; j < submenuItems.length; j++) {
					eachSubItem = submenuItems.item(j)
					if (1 == eachSubItem.nodeType) {
						if (true == exclusive) {
							optionValue = off;
							if (null != optionType) {
								eachSubItem.setAttribute(optionType, off);
							}
						}
						if (optionName == eachSubItem.getAttribute('id')) {
							targetItem = eachSubItem;
							if (null != optionType) {
								optionValue = targetItem.getAttribute(optionType);
							}
						}
					}
				}
			}
		}
	} 
	if (on == optionValue) {
		if (null != optionType) {
			targetItem.setAttribute(optionType, off);
		}
	} else if (off == optionValue) {
		if (null != optionType) {
			targetItem.setAttribute(optionType, on);
		}
	}
	
}

/************
**  SVG図面情報取得
************/
function getSvgInfo() {
	if (document.getElementsByTagName("z:manualid").item(0) != null) {
		manualId = document.getElementsByTagName("z:manualid").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:manualtitle").item(0) != null) {
		manualTitle = document.getElementsByTagName("z:manualtitle").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:blockid").item(0) != null) {
		blockId = document.getElementsByTagName("z:blockid").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:drawingtitle").item(0) != null) {
		drawingTitle = document.getElementsByTagName("z:drawingtitle").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:drawingid").item(0) != null) {
		drawingId = document.getElementsByTagName("z:drawingid").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:version").item(0) != null) {
		drawingVer = document.getElementsByTagName("z:version").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:timestamp").item(0) != null) {
		drawingTimestamp = document.getElementsByTagName("z:timestamp").item(0).getFirstChild.getData;
	}
	if (document.getElementsByTagName("z:scriptenable").item(0) != null) {
		scriptenable = document.getElementsByTagName("z:scriptenable").item(0).getFirstChild.getData;
	}
}

/************
**  ブラウザバージョン取得
************/
function getBrowserVersion() {
    str = parent.navigator.appName.toUpperCase();
	version = 0;
	appVer = parent.navigator.appVersion;
	if (str.indexOf("NETSCAPE") >= 0) {
		s = appVer.indexOf(" ",0);
		version = eval(appVer.substring(0,s));
		if (version >= 5) version++;
	}
	if (str.indexOf("MICROSOFT") >= 0) {
		appVer  = parent.navigator.userAgent;
		s = appVer.indexOf("MSIE ",0) + 5;
		e = appVer.indexOf(";",s);
		version = eval(appVer.substring(s,e));
	}
	return version;
}

/************
**  デフォルトコンテキストメニュー設定 & 部品デフォルトカラー属性ロード
************/
function defaultload(evt){
	var frame_name = parent.name;
	var p = parent.document.title.lastIndexOf('.');
	var svg_name = parent.document.title.substring(0, p);	// svgファイルの名前
	browserEval("if(parent != null && parent.frame2 != null){parent.frame2.defaultContextMemu('" + parent.name + "','" + svg_name + "','','')}");
}

/************
**  部品デフォルトカラーの設定
************/
function setDefaultColor(parts, col) {
	var layer, partsG, color, pid, cacheItem;
	var parts_piped = '|' + parts.toLowerCase() + '|';
	cacheItem = new Array;
	layer = rootG.firstChild;
	while (layer != null) {
		if (layer.nodeName == 'g') {
			partsG = layer.firstChild;
			while (partsG != null) {
				if (partsG.nodeName == 'g') {
					pid = '|' + partsG.getAttribute(':l').toLowerCase() + '|' ;
					if (pid.indexOf(parts_piped) != -1) {
						color = partsG.firstChild;
						while (color != null) {
							if (color.hasAttribute('fill')&&(color.getAttribute('fill')!='none')) { 
								color.setAttribute('z:cf', color.getAttribute('fill')); 
								color.setAttribute('fill', col);
							}
							if (color.hasAttribute('stroke')&&(color.getAttribute('fill')!='stroke')) { 
								color.setAttribute('z:cs', color.getAttribute('stroke')); 
								color.setAttribute('stroke', col);
							}
							cacheItem.push(color);
							//color.insertBefore(animT.cloneNode(false), color.firstChild);
							color = color.nextSibling;
						}
					}
				}
				partsG = partsG.nextSibling;
			}
		}
		layer = layer.nextSibling;
	}
}

/************
**  初期実行ルーチン
************/
var menuOpacity;
var menuReverse;
var layerMenu = new Array;
var layerMenuChecked = new Array;
var allLayerChecked;
var allLayerG = new Array;
var allLayerChecked = false;
var rootG = document.getElementById('root');
var svgG = document.firstChild;
var selected = null;
var menuComment;
var cache = new Array;
var cacheBBox = new Array;
var viewBox;
var animT = document.createElement('animate');

animT.setAttribute('accumulate', 'none');
animT.setAttribute('additive', 'replace');
animT.setAttribute('calcMode', 'discrete');
animT.setAttribute('fill', 'remove');
animT.setAttribute('restart', 'always');
animT.setAttribute('attributeName', 'opacity');
animT.setAttribute('dur', '3s');
animT.setAttribute('values', '1;0.25');
animT.setAttribute('repeatCount', 'indefinite');

var manualId = '';
var manualTitle = '';
var blockId = '';
var drawingTitle = '';
var drawingId = '';
var drawingVer = '';
var drawingTimestamp = '';
var scriptenable = 1;
var browserVersion = getBrowserVersion();

getSvgInfo();
rootG.addEventListener('SVGLoad', defaultload, false);

// カーソル形状をhandに変更するため<a>エレメントを生成し、<g>ルートを子ノードに設定する
//var a_node = document.createElement('a');
//a_node.appendChild(rootG);
//a_node.appendChild(document.getElementById('z|annotation'));
//svgG.appendChild(a_node);

menuSet();
readViewBox();

if (scriptenable == 1) {
	rootG.addEventListener('click', click, false);
}

